<?php
/**
 * Created by PhpStorm.
 * User: iqgmy
 * Date: 2020/10/23
 * Time: 2:02 PM
 */
namespace app\channel\model;
use app\BaseModel;
use think\Db;
//*------------------------------------------------------ */
//-- 奖励处理计算
/*------------------------------------------------------ */
class RewardLogRunModel extends BaseModel
{

    //*------------------------------------------------------ */
    //-- 获取充值升级货款相关
    //-- $user_id int 购买会员ID
    //-- $order_amount float 充值金额
    //-- return array 升级身份层级ID和实到帐金额
    /*------------------------------------------------------ */
    function getUplevelGoodsMoney($user_id,$order_amount){
        $ProxyLevelModel = new ProxyLevelModel();
        $ProxyUsersModel = new ProxyUsersModel();
        $userInfo = $ProxyUsersModel->info($user_id);
        $upLevel = [];
        if (bccomp($userInfo['proxyLevel']['uplevel_goods_money'], $order_amount, 2) == 0){
            $upLevel = $userInfo['proxyLevel'];
        }else{
            $proxyLevel = $ProxyLevelModel->getList();
            foreach ($proxyLevel as $level){
                if (bccomp($level['uplevel_goods_money'] - $userInfo['proxyLevel']['uplevel_goods_money'], $order_amount,2) == 0){
                    $upLevel = $level;
                    break;
                }
            }
        }

        if (empty($upLevel)){
            return '处理失败，没有找到相关升级货款设置.';
        }
        if ($userInfo['proxy_id'] == $upLevel['proxy_id']){//只有刚注册身份时出现
            $money = $upLevel['uplevel_goods_money_arrive'];
        }else{
            $money = $upLevel['uplevel_goods_money_arrive'] - $userInfo['proxyLevel']['uplevel_goods_money_arrive'];
        }
        $data['up_proxy_id'] = $upLevel['proxy_id'];
        $data['realMoney'] = $money;
        return $data;
    }
    //*------------------------------------------------------ */
    //-- 升级货款奖励处理
    //-- $user_id int 购买会员ID
    //-- $order_id int 充值订单ID
    //-- $order_amount float 充值金额
    //-- $up_proxy_id int 升级身份层级ID
    //-- return array 升级对应的身份信息和实到帐金额
    /*------------------------------------------------------ */
    function tzsjjlRun($user_id,$order_id,$order_amount,$up_proxy_id){
        $RewardModel = new RewardModel();
        //孝道基金
        $reward = $RewardModel->where('reward_type','xdjj')->find();
        $rewardInfo = json_decode($reward['info'],true);
        $rewardPer = $rewardInfo['deduct_per'];
        $rewardMoney = $order_amount / 100 * $rewardPer;
        if ($rewardMoney <= 0){
            return true;
        }
        $inData['reward_type'] = 'xdjj';
        $inData['reward_name'] = '孝行天下，爱心联盟';
        $inData['reward_info'] = '充值升级货款：'.$order_amount.'，扣：'.$rewardPer.'%到基金.';
        $inData['reward_money'] = $rewardMoney;
        $inData['to_uid'] = 0;
        $inData['to_proxy_id'] = 0;
        $inData['from_uid'] = $user_id;
        $inData['from_proxy_id'] = $up_proxy_id;
        $inData['from_type'] = 'recharge';
        $inData['from_id'] = $order_id;
        $inData['status'] = 2;//立即返
        $inData['add_time'] = time();
        $res = $this->create($inData);
        if ($res->id < 1){
            return false;
        }
        $upData['ext_count'] = ['INC',$rewardMoney];
        $res = $RewardModel->where('reward_type','xdjj')->update($upData);
        if ($res < 1){
            return false;
        }
        //孝道基金end

        $ProxyUsersModel = new ProxyUsersModel();
        $userInfo = $ProxyUsersModel->info($user_id);
        if ($userInfo['pid'] < 1){
            return true;//没有上级，直接返回成功
        }
        //直推升级奖励
        $pUserInfo = $ProxyUsersModel->info($userInfo['pid']);
        $reward = $RewardModel->where('reward_type','tzsjjl')->find();
        $rewardInfo = json_decode($reward['info'],true);
        $rewardInfo = $rewardInfo[$pUserInfo['proxy_id']];
        $rewardPer = $rewardInfo[$up_proxy_id];
        $rewardMoney = $order_amount / 100 * $rewardPer;
        if ($rewardMoney <= 0){
            return true;
        }
        $WalletModel = new WalletModel();
        $ProxyLevelModel = new ProxyLevelModel();
        $upLevel = $ProxyLevelModel->info($up_proxy_id);
        $inData['reward_type'] = 'tzsjjl';
        $inData['reward_name'] = '直推升级奖励';
        $inData['reward_info'] = '直推推下级充值升级货款：'.$order_amount.'，升级身份：'.$upLevel['proxy_name'].'，奖励.'.$rewardPer.'%';
        $inData['reward_money'] = $rewardMoney;
        $inData['to_uid'] = $pUserInfo['user_id'];
        $inData['to_proxy_id'] = $pUserInfo['proxy_id'];
        $inData['from_uid'] = $user_id;
        $inData['from_proxy_id'] = $up_proxy_id;
        $inData['from_type'] = 'recharge';
        $inData['from_id'] = $order_id;
        $inData['status'] = 2;//立即返
        $inData['add_time'] = time();
        $res = $this->create($inData);
        if ($res->id < 1){
            return false;
        }
        $changedata['change_desc'] = $inData['reward_info'];
        $changedata['change_type'] = 9;
        $changedata['balance_money'] = $rewardMoney;
        $changedata['total_brokerage'] = $rewardMoney;
        $res = $WalletModel->change($changedata, $pUserInfo['user_id'],false);
        if ($res !== true) {
            return false;
        }

        //市场补贴奖励
        if ($pUserInfo['pid'] < 1){
            return true;//没有上级，直接返回成功
        }
        $jpUserInfo = $ProxyUsersModel->info($pUserInfo['pid']);
        $reward = $RewardModel->where('reward_type','tzsjjlb')->find();
        $rewardInfo = json_decode($reward['info'],true);
        $rewardInfo = $rewardInfo[$jpUserInfo['proxy_id']];
        $rewardPer = $rewardInfo[$pUserInfo['proxy_id']];//根据直推代理的层级计算
        $rewardMoney = $order_amount / 100 * $rewardPer;
        if ($rewardMoney <= 0){
            return true;
        }
        $inData['reward_type'] = 'tzsjjlb';
        $inData['reward_name'] = '市场补贴奖励';
        $inData['reward_info'] = '间推下级充值升级货款：'.$order_amount.'，直推下级身份：'.$pUserInfo['proxyLevel']['proxy_name'].'，奖励.'.$rewardPer.'%';
        $inData['reward_money'] = $rewardMoney;
        $inData['to_uid'] = $jpUserInfo['user_id'];
        $inData['to_proxy_id'] = $jpUserInfo['proxy_id'];
        $inData['from_uid'] = $user_id;
        $inData['from_proxy_id'] = $up_proxy_id;
        $inData['from_type'] = 'recharge';
        $inData['from_id'] = $order_id;
        $inData['status'] = 2;//立即返
        $inData['add_time'] = time();
        $res = $this->create($inData);
        if ($res->id < 1){
            return false;
        }
        $changedata['change_desc'] = $inData['reward_info'];
        $changedata['change_type'] = 9;
        $changedata['balance_money'] = $rewardMoney;
        $changedata['total_brokerage'] = $rewardMoney;
        $res = $WalletModel->change($changedata, $jpUserInfo['user_id'],false);
        if ($res !== true) {
            return false;
        }
        return true;
    }
    //*------------------------------------------------------ */
    //-- 直推升级奖励
    /*------------------------------------------------------ */
    public function tzsRecommend($user_id,$order_id,$order_amount,$order){
        $RewardModel = new RewardModel();
        $ProxyUsersModel = new ProxyUsersModel();
        $ProxyLevelModel = new ProxyLevelModel();
        $RewardLogModel = new RewardLogModel();
        $WalletModel = new WalletModel();
        $userInfo = $ProxyUsersModel->info($user_id);
        // if ($userInfo['pid'] < 1 || $userInfo['pid'] == $userInfo['supply_uid']) return true; // 没有上级/上级是拿货上级，直接返回成功
        // 升级身份
        $level = $ProxyLevelModel->info($order['proxy_id']);
        if($level['level'] >= $userInfo['proxyLevel']['level']) return true; // 不必升级
        if($userInfo['pid'] > 0){
            // 上级
            $pUserInfo = $ProxyUsersModel->info($userInfo['pid']);

            // 是代理身份
            //代理上级和拿货上级一样不再奖励
            if($pUserInfo['proxy_id'] > 0 && $order['supply_uid'] != $order['user_pid']){
                // 判断是否拿过奖励
                //$check = $RewardLogModel->where('to_uid', $pUserInfo['user_id'])->where('reward_type', 'tzsjjl')->count();
                $check = $RewardLogModel->where('to_uid', $pUserInfo['user_id'])
                    ->where('from_up_proxy_id', $order['proxy_id'])
                    ->where('reward_type', 'tzsjjl')->count();
                if($check < 1){ // 可拿直推奖励
                    $proxy_id = $order['proxy_id'];
                    // 判断级别是否超过上级
                    $ProxyLevelList = (new ProxyLevelModel)->getList();
                    $supply_uid = (new ProxyUsersModel())->getSupplyUid($user_id, $proxy_id, $ProxyLevelList);
                    if ($supply_uid != $pUserInfo['proxy_id']){
                        $proxy_id = $pUserInfo['proxy_id'];
                    }
                    //直推升级奖励
                    $reward = $RewardModel->where('reward_type','tzsjjl')->find();
                    $rewardInfo = json_decode($reward['info'],true);
                    $rewardInfo = $rewardInfo[$pUserInfo['proxy_id']];
                    //$rewardPer = $rewardInfo[$order['proxy_id']];
                    $rewardPer = $rewardInfo[$proxy_id];
                    if($rewardPer > 0){ // 有奖励
                        //$cardinal_award = ($level['replenish_money'] - $userInfo['proxyLevel']['replenish_money']) * $rewardPer / 100;
                        $cardinal_award = ($level['earnest_money'] - $userInfo['proxyLevel']['earnest_money']) * $rewardPer / 100;
                        if($userInfo['supply_uid'] < 1){ // 供货上级是平台
                            $status = 2;
                            $tzsjjl_change['balance_money'] = $cardinal_award;
                            $tzsjjl_change['change_type'] = 9;
                            $tzsjjl_change['change_desc'] = '推荐下级升级奖励';
                            $tzsjjl_change['by_id'] = $order_id;
                            $res = $WalletModel->change($tzsjjl_change, $pUserInfo['user_id']);
                            if($res !== true) return false;
                        } else { // 供货上级是代理
                            $status = 1;
                        }
                        // 添加记录
                        $tzsjjl_data = [
                            'reward_type' => 'tzsjjl',
                            'reward_name' => '推荐下级升级奖励',
                            'reward_info' => '下级用户，ID：'.$user_id.'升级为'.$level['proxy_name'],
                            'reward_money' => $cardinal_award,
                            'to_uid' => $pUserInfo['user_id'],
                            'to_proxy_id' => $pUserInfo['proxy_id'],
                            'from_uid' => $user_id,
                            //'from_proxy_id' => $userInfo['proxyLevel']['proxy_name'],
                            'from_proxy_id' => $userInfo['proxyLevel']['proxy_id'],
                            'from_up_proxy_id' => $order['proxy_id'],
                            'from_type' => 'recharge',
                            'from_id' => $order_id,
                            'payer_uid' => $userInfo['supply_uid'],
                            'supply_uid' => $order['supply_uid'],
                            'status' => $status,
                            'add_time' => time(),
                            'is_log' => 1,
                            'surrender_order_status' => 1,
                            'reward_per' => $rewardPer
                        ];
                        $res = $RewardLogModel->insert($tzsjjl_data);
                        if($res < 1) return false;
                    }
                }
            }
        }
        $earnest_money = $WalletModel->where('user_id', $userInfo['user_id'])->value('earnest_money');
        // 是否扣除原来的保证金
        if($userInfo['supply_uid'] != $order['supply_uid'] && $earnest_money > 0){
            $out_data['earnest_money'] = $earnest_money * -1;
            $out_data['change_type'] = 4;
            $out_data['change_desc'] = '非原供货上级，扣除保证金';
            $out_data['by_id'] = $order_id;
            $res = $WalletModel->change($out_data, $userInfo['user_id']);
            if($res !== true) return false;
        }
        // 代理升级
        $res = (new ProxyUsersModel())->upInfo($order['user_id'], [
            'uplevel_time' => time(),
            'supply_uid' => $order['supply_uid'],
            'proxy_id' => $order['proxy_id']
        ]);
        if($res < 1) return false;
        return true;
    }

    /*------------------------------------------------------ */
    //-- 订单奖项计算
    /*------------------------------------------------------ */
    public function runByOrder(&$orderInfo){
        $RewardModel = new RewardModel();
        /*$ChannelGoodsModel = new ChannelGoodsModel();
        $GoodsModel = new \app\shop\model\GoodsModel();*/
        $ProxyLevelModel = new ProxyLevelModel();
        $ProxyUsersModel = new ProxyUsersModel();
        $RewardLogModel = new RewardLogModel();
        $setting = settings();
        $time = time();
        if ($orderInfo['purchase_type'] > 1) {
            // 区域奖
            $ProxyUserRegionModel = new ProxyUserRegionModel();
            $where = [];
            $where[] = ['region_id', 'IN', [$orderInfo['province'], $orderInfo['city'], $orderInfo['district']]];
            $proxyUserRegion = $ProxyUserRegionModel->where($where)->column('user_id', 'region_id');
            // 奖项
            $reward = $RewardModel->where('reward_type', 'qyj')->find();
            $rewardInfo = json_decode($reward['info'], true);
            if (empty($proxyUserRegion) == false) {//不为空即有区域代理
                $regionProxy = ['province' => '省代', 'city' => '市代', 'district' => '区代'];
                foreach ($rewardInfo as $key => $reward) {
                    if (empty($proxyUserRegion[$orderInfo[$key]]) == false) {
                        if (empty($regionProxy[$key])) {
                            return '计算区域奖励失败，未知定义.';
                        }
                        $rewardPer = $rewardInfo[$key];
                        $inData['reward_type'] = 'qyj';
                        $inData['reward_name'] = '区域奖 - ' . $regionProxy[$key];
                        $inData['reward_info'] = '商品金额：' . $orderInfo['goods_amount'] . '，' . $regionProxy[$key] . '奖励：' . $rewardPer . '%;';
                        $inData['reward_money'] = $orderInfo['goods_amount'] / 100 * $rewardPer;
                        $inData['to_uid'] = $proxyUserRegion[$orderInfo[$key]];
                        $inData['to_proxy_id'] = 0;
                        $inData['from_uid'] = $orderInfo['user_id'];
                        $inData['from_proxy_id'] = $orderInfo['user_proxy_id'];
                        $inData['from_type'] = 'order';
                        $inData['from_id'] = $orderInfo['order_id'];
                        $inData['status'] = 1;//支付成功后，都设为待返
                        $inData['add_time'] = $time;
                        $res = $this->create($inData);
                        if ($res->id < 1) {
                            return '计算区域奖励失败';
                        }
                    }
                }
            }
            if($orderInfo['user_pid'] > 0){
                // 国代
                $max = $ProxyLevelModel->order('level', 'asc')->value('proxy_id');
                $country = $ProxyUsersModel->findCountry($orderInfo['user_pid'], $max);
                if($country > 0){ // 国代
                    $country_user = $ProxyUsersModel->info($country);
                    $rewardPer = $rewardInfo['country'];
                    $inData['reward_type'] = 'qyj';
                    $inData['reward_name'] = '区域奖 - 国代';
                    $inData['reward_info'] = '商品金额：' . $orderInfo['goods_amount'] . '，国代，奖励：' . $rewardPer . '%;';
                    $inData['reward_money'] = $orderInfo['goods_amount'] / 100 * $rewardPer;
                    $inData['to_uid'] = $country_user['user_id'];
                    $inData['to_proxy_id'] = $country_user['proxy_id'];
                    $inData['from_uid'] = $orderInfo['user_id'];
                    $inData['from_proxy_id'] = $orderInfo['user_proxy_id'];
                    $inData['from_type'] = 'order';
                    $inData['from_id'] = $orderInfo['order_id'];
                    $inData['status'] = 1;//支付成功后，都设为待返
                    $inData['add_time'] = $time;
                    $res = $this->create($inData);
                    if ($res->id < 1) {
                        return '计算区域奖励失败';
                    }
                }
            }
            // 区域奖end
        }

        if ($orderInfo['purchase_type'] >= 3){//提货订单不执行以下
            return true;
        }

        //计算出货代理的收益
        /*if ($orderInfo['supply_uid'] > 0){
            $totalPurchasePrice = 0;//进货总价
            $rewardDetail = [];
            //获取当前供货商的供货上级，用于查询当前供货商进货价
            $supplyInfo = (new ProxyLevelModel)->info($orderInfo['supply_proxy_id']);
            $top_supply_pid = $supplyInfo['supply_pid'];
            //end

            //根据出货代理的层级，计算出货代理的成本价
            foreach ($orderInfo['goodsList'] as $goods){
                $_goods = $ChannelGoodsModel->where('goods_id',$goods['goods_id'])->field('price_type,pricing_type')->find();
                if ($goods['sku_id'] > 0){
                    $goods['is_spec'] = 1;
                }else{
                    $goods['shop_price'] = $GoodsModel->where('goods_id',$goods['goods_id'])->value('shop_price');
                }
                $goods['price_type'] = $_goods['price_type'];
                $goods['pricing_type'] = $_goods['pricing_type'];

                $prices = $ChannelGoodsModel->getPrcies($goods,$top_supply_pid);//获取出货代理的进货价
                $purchasePrice = $prices[$goods['sku_id']];
                $purchasePriceTotal = $purchasePrice['price'] * $goods['real_number'];
                $totalPurchasePrice += $purchasePriceTotal;
                $detail = '商品:'.$goods['goods_name'];
                if ($goods['sku_id'] > 0){
                    $detail .= " - ".$goods['sku_name'];
                }
                $salePriceTotal = $goods['sale_price'] * $goods['real_number'];
                $diffPriceTotal = $salePriceTotal - $purchasePriceTotal;
                $detail .= '_出货价:'.$goods['sale_price'].'_进货价:'.$purchasePrice['price'].'_数量:'.$goods['real_number'];
                $detail .= '_出货收益:'.$salePriceTotal;
                $detail .= '_差价收益:'.$diffPriceTotal;
                $rewardDetail[] = $detail;
            }

            $inData['reward_type'] = 'purchase';
            $inData['reward_name'] = '出货收益';
            $inData['reward_info'] =  join('，',$rewardDetail);
            if ($orderInfo['shipping_fee'] > 0){
                $inData['reward_info'] .= '到帐收益中包括运费:'.$orderInfo['shipping_fee'];
            }
            $inData['reward_money'] = $orderInfo['order_amount'];
            $inData['is_log'] = 0;
            if ($setting['channel_receive_payment_set'] == 1 && $orderInfo['pay_code'] == 'offline'){ //非平台统一收款，线下收款是打款给供货代理，只记录奖项
                $inData['is_log'] = 1;
                $inData['reward_info'] .= '，供货代理已线下收款';
            }

            $inData['to_uid'] = $orderInfo['supply_uid'];
            $inData['to_proxy_id'] = $orderInfo['supply_proxy_id'];
            $inData['from_uid'] = $orderInfo['user_id'];
            $inData['from_proxy_id'] = $orderInfo['user_proxy_id'];;
            $inData['from_type'] = 'order';
            $inData['from_id'] = $orderInfo['order_id'];
            if ($inData['is_log'] == 1){//只记录时
                $inData['status'] = 2;//已返，供货代理已线下收款
            }elseif ($orderInfo['purchase_type'] == 1){//云仓立返
                $inData['status'] = 1;//待返
            }else{//签收后返
                $inData['status'] = 0;
            }
            $inData['add_time'] = $time;
            $res = $this->save($inData);
            if ($res < 1){
                return '计算出货代理的收益失败';
            }
        }*/
        //计算出货代理的收益end

        //如果出货代理与推荐者不一致且是代理身份，推荐者享受补货奖励
        if ($orderInfo['user_pid'] > 0 && $orderInfo['user_pid'] != $orderInfo['supply_uid'] &&
            $orderInfo['user_pid_proxy_id'] > 0 && $orderInfo['user_proxy_id'] > 0){
            $reward = $RewardModel->where('reward_type','bhjl')->find();
            $rewardInfo = json_decode($reward['info'],true);
            $rewardInfo = $rewardInfo[$orderInfo['user_pid_proxy_id']];
            $rewardPer = $rewardInfo[$orderInfo['user_proxy_id']];
            if($rewardPer > 0){
                $user = $ProxyUsersModel->info($orderInfo['user_id']);
                $p_user = $ProxyUsersModel->info($orderInfo['user_pid']);
                if($p_user['proxy_id'] == $orderInfo['user_proxy_id']){ // 平级补货奖
                    $inData['reward_type'] = 'bhjl';
                    $inData['reward_name'] = '平级补货奖';
                    $inData['reward_info'] = '商品金额：'.$orderInfo['goods_amount'].'，奖励：'.$rewardPer.'%';
                    $inData['reward_money'] = $orderInfo['goods_amount'] / 100 * $rewardPer;
                    $inData['to_uid'] = $orderInfo['user_pid'];
                    $inData['to_proxy_id'] = $orderInfo['user_pid_proxy_id'];
                    $inData['from_uid'] = $orderInfo['user_id'];
                    $inData['from_proxy_id'] = $orderInfo['user_proxy_id'];
                    $inData['from_type'] = 'order';
                    $inData['from_id'] = $orderInfo['order_id'];
                    if ($setting['channel_receive_payment_set'] == 1 && $orderInfo['pay_code'] == 'offline'){ //非平台统一收款，线下收款是打款给供货代理，只记录奖项
                        $inData['payer_uid'] = $orderInfo['supply_uid'];//记录奖励支付人，0为平台
                    }
                    if ($orderInfo['purchase_type'] == 1){//云仓立返
                        $inData['status'] = 1;//待返
                    }else{//签收后返
                        $inData['status'] = 0;
                    }
                    $inData['add_time'] = $time;
                    $res = $RewardLogModel->insert($inData);
                    if ($res < 1){
                        return '计算平级补货奖失败';
                    }
                }
                if($user['proxyLevel']['level'] < $p_user['proxyLevel']['level']){ // 低推高
                    // 判断是否拿过奖励
                    $check = $RewardLogModel->where('to_uid', $p_user['user_id'])->where('reward_type', 'dtgbh')->count();
                    if($check < 1){ // 可拿奖励
                        $inData['reward_type'] = 'dtgbh';
                        $inData['reward_name'] = '低推高补货奖';
                        $inData['reward_info'] = '商品金额：'.$orderInfo['goods_amount'].'，奖励：'.$rewardPer.'%';
                        $inData['reward_money'] = $orderInfo['goods_amount'] / 100 * $rewardPer;
                        $inData['to_uid'] = $orderInfo['user_pid'];
                        $inData['to_proxy_id'] = $orderInfo['user_pid_proxy_id'];
                        $inData['from_uid'] = $orderInfo['user_id'];
                        $inData['from_proxy_id'] = $orderInfo['user_proxy_id'];
                        $inData['from_type'] = 'order';
                        $inData['from_id'] = $orderInfo['order_id'];
                        if ($setting['channel_receive_payment_set'] == 1 && $orderInfo['pay_code'] == 'offline'){ //非平台统一收款，线下收款是打款给供货代理，只记录奖项
                            $inData['payer_uid'] = $orderInfo['supply_uid'];//记录奖励支付人，0为平台
                        }
                        if ($orderInfo['purchase_type'] == 1){//云仓立返
                            $inData['status'] = 1;//待返
                        }else{//签收后返
                            $inData['status'] = 0;
                        }
                        $inData['add_time'] = $time;
                        $res = $RewardLogModel->insert($inData);
                        if ($res < 1){
                            return '计算低推高补货奖失败';
                        }
                    }
                }
            }
        }
        //推荐者享受补货奖励end
        return true;
    }

    /*------------------------------------------------------ */
    //-- 计算创业金 根据升级时间每10天计算一次
    //-- $istest bool 是否测试
    /*------------------------------------------------------ */
    public function runCyj($istest = false)
    {
        $RewardModel = new RewardModel();
        $reward = $RewardModel->where('reward_type','cyj')->find();
        $rewardInfo = json_decode($reward['info'],true);
        $proxy_ids = [];
        //查询所有参与创业金的代理层级
        foreach ($rewardInfo as $key=>$proxy){
            if ($proxy['is_join'] == 1){
                $proxy_ids[] = $key;
            }
        }
        if (empty($proxy_ids) == true){
            return true;//没有找到终止
        }
        $ProxyUsersModel = new ProxyUsersModel();
        $WalletModel = new WalletModel();
        $RechargeLogModel = new RechargeLogModel();
        $where = [];
        $where[] = ['proxy_id','IN',$proxy_ids];
        $userList = $ProxyUsersModel->where($where)->select()->toArray();

        $time = time();
        $start_time = strtotime(date('Y/m/01', strtotime("-1 months")));
        $end_time =  strtotime(date('Y/m/01')) - 1;
        foreach ($userList as $user){
            if ($user['uplevel_time'] > $start_time){//没有最近执行时间，使用升级时间计算
                $runTime = $user['uplevel_time'];
            }else{
                $runTime = $start_time;
            }

            if ($istest == true){//测试时使用
                $endTime = $time;
            }else{
                $endTime = $end_time;
            }
            $where = [];
            $where[] = ['user_pid','=',$user['user_id']];
            /*$where[] = ['status','=',9];*/
            $where[] = ['order_status', '=', 1];
            $where[] = ['pay_status', '=', 1];
            $where[] = ['pay_time','between',[$runTime,$endTime]];
            // $totalMoney = $RechargeLogModel->where($where)->SUM('order_amount');
            $totalMoney = (new OrderModel())->where($where)->SUM('order_amount');
            $distance = $rewardInfo[$user['proxy_id']]['distance'];
            $rewardPer = 0;
            foreach ($distance['min'] as $key=>$min){
                $min = $min * 10000;
                $max = $distance['max'][$key] * 10000;
                if ($totalMoney >= $min){
                    if ($totalMoney < $max){
                        $rewardPer = $distance['val'][$key];
                    }elseif($totalMoney >= $max){
                        $rewardPer = $distance['val'][$key];
                    }
                }
            }

            $inData['reward_type'] = 'cyj';
            $inData['reward_name'] = '创业金';
            if ($istest == true){
                $inData['reward_name'] .= 'by测试';
            }
            $inData['reward_info'] = '直推升级补货汇总:'.date('Y-m-d',$runTime).'至'.date('Y-m-d',$endTime)."，合计补货：".$totalMoney.'，奖励：'.$rewardPer.'%';
            $inData['reward_money'] = $totalMoney / 100 * $rewardPer;
            $inData['to_uid'] = $user['user_id'];
            $inData['to_proxy_id'] = $user['proxy_id'];
            $inData['from_type'] = 'recharge';
            $inData['status'] = 2;//立即到帐
            $inData['add_time'] = $time;
            $res = $this->create($inData);
            if ($res->id < 1){
                return '计算创业金奖励失败';
            }

            if ($inData['reward_money'] > 0){
                $changedata['change_desc'] = '创业金-'.$inData['reward_info'];
                $changedata['change_type'] = 9;
                $changedata['balance_money'] =  $inData['reward_money'];
                $changedata['total_brokerage'] = $inData['reward_money'];
                $res = $WalletModel->change($changedata, $user['user_id'],false);
                if ($res !== true) {
                    return '更新代理帐户失败.';
                }
            }

        }
        return true;
    }
    /*------------------------------------------------------ */
    //-- 计算月分红 根据升级时间每月计算一次
    //-- $istest bool 是否测试
    /*------------------------------------------------------ */
    public function runYfh($istest = false)
    {
        $RewardModel = new RewardModel();
        $reward = $RewardModel->where('reward_type','yfh')->find();
        $rewardInfo = json_decode($reward['info'],true);
        $join_proxy_id = [];//参与月分红的代理层级
        foreach ($rewardInfo as $key=>$info){
            if ($info['is_join'] == 1){
                $join_proxy_id[] = $key;
            }
        }
        $ProxyUsersModel = new ProxyUsersModel();
        $where = [];
        $where[] = ['proxy_id','in',$join_proxy_id];
        $where[] = ['status','=',1];
        $users = $ProxyUsersModel->where($where)->column('user_id,pid,proxy_id');

        //时间处理
        if ($istest == true) {//测试时使用
            $start_time = strtotime(date('Y/m/01', strtotime("-1 months")));
            $end_time = time();
        }else{
            $start_time = strtotime(date('Y/m/01', strtotime("-1 months")));
            $end_time =  strtotime(date('Y/m/01')) - 1;
        }
        $timeWhere = [$start_time,$end_time];

        $WalletModel = new WalletModel();
        // $RechargeLogModel = new RechargeLogModel();
        $OrderModel = new OrderModel();
        $UsersBindSuperiorModel = new \app\member\model\UsersBindSuperiorModel();
        $stat = [];//统计结果
        $pUsers = [];
        foreach ($users as $user){
            $pUsers[$user['pid']][] = $user['user_id'];
            $where = [];
            $where[] = ['', 'exp', Db::raw("FIND_IN_SET('" . $user['user_id'] . "',superior)")];
            // 所有下级
            $uIds = $UsersBindSuperiorModel->where($where)->column('user_id');
            // 统计的身份会员
            $role_uids = $ProxyUsersModel->whereIn('user_id', $uIds)
                ->where('proxy_id', 'in', $join_proxy_id)->column('user_id,proxy_id,pid','user_id');
            // 不统计的会员
            /*$no_role_uids = $ProxyUsersModel->whereIn('user_id', $uIds)
                ->whereNotIn('proxy_id', $join_proxy_id)->column('user_id,proxy_id,pid','user_id');*/
            // 条件
            $where = [];
            $where[] = ['purchase_type', 'in', [1,2]];
            $where[] = ['order_status', '=', 1];
            $where[] = ['add_time','between',$timeWhere];
            // 统计直接找平台补货的
            /*$no_role_amount = $OrderModel->where($where)->where('supply_uid', 0)
                ->whereIn('user_id', array_column($no_role_uids,'user_id'))->sum('order_amount');*/
            // 身份下级的
            $role_amount = $OrderModel->where($where)->whereIn('user_id', array_column($role_uids, 'user_id'))
                ->sum('order_amount');
            // 奖励基数
            $distance = $rewardInfo[$user['proxy_id']]['distance'];
            // $totalMoney = $no_role_amount + $role_amount;
            $totalMoney = $role_amount;
            $rewardPer = 0;//计算比例
            foreach ($distance['min'] as $key=>$min){
                $min = $min * 10000;
                $max = $distance['max'][$key] * 10000;
                if ($totalMoney >= $min){
                    if ($totalMoney < $max){
                        $rewardPer = $distance['val'][$key];
                    }elseif($totalMoney >= $max){
                        $rewardPer = $distance['val'][$key];
                    }
                }
            }
            $stat[$user['user_id']]['proxy_id'] = $user['proxy_id'];
            $stat[$user['user_id']]['role_amount'] = $role_amount;
            $stat[$user['user_id']]['rewardPer'] = $rewardPer;
            $stat[$user['user_id']]['totalMoney'] = $totalMoney;
            $stat[$user['user_id']]['distanceMoney'] = $totalMoney / 100 * $rewardPer;
            unset($role_uids[$user['user_id']]);
            $stat[$user['user_id']]['role_users'] = $role_uids;
        }
        $time = time();
        foreach ($stat as $uid => $row){
            $reward_money = $row['distanceMoney'];
            $log = "，减去团队内同级明细：";
            $cutLog = [];
            foreach ($row['role_users'] as $val){
                $reward_money -= $stat[$val]['distanceMoney'];
                $_log = '【用户ID：'.$val['user_id']."】总业绩：￥".$stat[$val['user_id']]['totalMoney'];
                $_log .= '，对应业绩区间的比例：'.$stat[$val['user_id']]['rewardPer'].'%，共：￥'.$stat[$val['user_id']]['distanceMoney'];
                $cutLog[] = $_log;
            }
            if ($reward_money < 0){
                $reward_money = 0;
            }
            if (empty($cutLog) == false){
                $log .= join('，',$cutLog);
            }else{
                $log .= '【无直推同级】';
            }
            $inData['reward_type'] = 'yfh';
            $inData['reward_name'] = '月分红';
            if ($istest == true){
                $inData['reward_name'] .= 'by测试';
            }
            $inData['reward_info'] = '时间:'.date('Y-m-d H:i:s',$start_time).'至'.date('Y-m-d H:i:s',$end_time);
            $inData['reward_info'] .= "，本人和团队的总业绩：￥".$row['totalMoney'];
            $inData['reward_info'] .= "，对应业绩区间的比例：".$row['rewardPer'].'%';
            $inData['reward_info'] .= $log;
            $inData['reward_info'] .= '，实得：￥'.$reward_money;
            $inData['reward_money'] = $reward_money;
            $inData['to_uid'] = $uid;
            $inData['to_proxy_id'] = $row['proxy_id'];
            $inData['from_type'] = 'order_recharge';
            $inData['status'] = 2;//立即到帐
            $inData['add_time'] = $time;
            $res = $this->create($inData);
            if ($res->id < 1){
                return '计算月分红奖励失败';
            }
            if ($inData['reward_money'] > 0){
                $changedata['change_desc'] = '月分红';
                $changedata['change_type'] = 9;
                $changedata['balance_money'] =  $inData['reward_money'];
                $changedata['total_brokerage'] = $inData['reward_money'];
                $res = $WalletModel->change($changedata, $uid,false);
                if ($res !== true) {
                    return '更新代理帐户失败.';
                }
            }
        }
        return true;
    }
}